import { defineConfig,loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import fs from 'fs'

import path from 'path'
const pathSrc = path.resolve(__dirname, 'src')
 
// https://vite.dev/config/
export default defineConfig( ({mode}) => {
  const envConfig = loadEnv(mode, process.cwd());
  return {
    server:{
      https: {
        // 此处仅限本地 locahost 和 127.0.0.1地址，使用mkcert生成的证书
        key: fs.readFileSync('./certs/127.0.0.1+1-key.pem'),  
        cert: fs.readFileSync('./certs/127.0.0.1+1.pem'),
      },
      host: '0.0.0.0',
      port: parseInt(envConfig.VITE_APP_PORT),
      proxy:  {
        '/api': {
          target: envConfig.VITE_API_BASE_URL,
          changeOrigin: true,
          // rewrite: (path) => path.replace(/^\/api/, ''), // 重写路径,此处由于后端设置/api路由代理，故不必要
          websockets: true, // 代理 WebSocket
          secure: false, // 在开发环境中跳过 SSL 证书验证
        }
      },
    },
    build: {
      outDir: mode === 'prod' ? 'dist/prod' : 'dist/dev',
    },
    plugins: [
      vue(),
      vueDevTools(),
      AutoImport({
        imports:['vue','vue-router','pinia'],
        resolvers: [
          ElementPlusResolver(),
          IconsResolver({
            // prefix: 'Icon',
            //去掉前缀
            prefix: false,
            enabledCollections: [''],
          }),
        ],
        dts: path.resolve(pathSrc, 'auto-imports.d.ts'),
      }),
      Components({
        resolvers: [
          // 自动导入 Element Plus 组件
          ElementPlusResolver(),
          // 自动注册图标组件
          IconsResolver({
            //去掉前缀
            prefix: false,
            enabledCollections: [''],
          }),],
          dts: path.resolve(pathSrc, 'components.d.ts'),
      }),
      Icons({
        autoInstall: true,
      }),
    ],
    resolve: {
      alias: {
        // '@': fileURLToPath(new URL('./src', import.meta.url))
        '@': pathSrc,
      },
    },
  }
})
